/***********************************************************************
 *            Project: CoreCms
 *        ProjectName: 核心内容管理系统                                
 *                Web: https://www.corecms.net                      
 *             Author: 大灰灰                                          
 *              Email: jianweie@163.com                                
 *         CreateTime: 2022/9/16 20:41:09
 *        Description: 暂无
 ***********************************************************************/


using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using CoreCms.Net.Configuration;
using CoreCms.Net.Model.Entities;
using CoreCms.Net.Model.Entities.Expression;
using CoreCms.Net.Model.FromBody;
using CoreCms.Net.Model.ViewModels.UI;
using CoreCms.Net.Filter;
using CoreCms.Net.IServices;
using CoreCms.Net.Utility.Helper;
using CoreCms.Net.Utility.Extensions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using Newtonsoft.Json;
using CoreCms.Net.Model.ViewModels.YiLianYun;
using CoreCms.Net.Web.Admin.Infrastructure;
using Flurl.Http;

namespace CoreCms.Net.Web.Admin.Controllers
{
    /// <summary>
    /// 打印机列表
    ///</summary>
    [Description("打印机列表")]
    [Route("api/[controller]/[action]")]
    [ApiController]
    [RequiredErrorForAdmin]
    [Authorize(Permissions.Name)]
    public class CoreCmsPrinterController : ControllerBase
    {
        private readonly IWebHostEnvironment _webHostEnvironment;
        private readonly ICoreCmsPrinterServices _coreCmsPrinterServices;
        private readonly ICoreCmsStoreServices _storeServices;


        /// <summary>
        /// 构造函数
        ///</summary>
        public CoreCmsPrinterController(IWebHostEnvironment webHostEnvironment
            , ICoreCmsPrinterServices coreCmsPrinterServices, ICoreCmsStoreServices storeServices)
        {
            _webHostEnvironment = webHostEnvironment;
            _coreCmsPrinterServices = coreCmsPrinterServices;
            _storeServices = storeServices;
        }

        #region 获取列表============================================================
        // POST: Api/CoreCmsPrinter/GetPageList
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Description("获取列表")]
        public async Task<AdminUiCallBack> GetPageList()
        {
            var jm = new AdminUiCallBack();
            var pageCurrent = Request.Form["page"].FirstOrDefault().ObjectToInt(1);
            var pageSize = Request.Form["limit"].FirstOrDefault().ObjectToInt(30);
            var where = PredicateBuilder.True<CoreCmsPrinter>();
            //获取排序字段
            var orderField = Request.Form["orderField"].FirstOrDefault();

            Expression<Func<CoreCmsPrinter, object>> orderEx = orderField switch
            {
                "id" => p => p.id,
                "name" => p => p.name,
                "code" => p => p.code,
                "clientId" => p => p.clientId,
                "clientSecret" => p => p.clientSecret,
                "machineCode" => p => p.machineCode,
                "msign" => p => p.msign,
                "printerName" => p => p.printerName,
                "phone" => p => p.phone,
                "accessToken" => p => p.accessToken,
                "refreshToken" => p => p.refreshToken,
                "expiresIn" => p => p.expiresIn,
                "expiressEndTime" => p => p.expiressEndTime,
                "parameters" => p => p.parameters,
                "createTime" => p => p.createTime,
                "isDefault" => p => p.isDefault,
                "isOpen" => p => p.isOpen,
                "storeId" => p => p.storeId,
                _ => p => p.id
            };

            //设置排序方式
            var orderDirection = Request.Form["orderDirection"].FirstOrDefault();
            var orderBy = orderDirection switch
            {
                "asc" => OrderByType.Asc,
                "desc" => OrderByType.Desc,
                _ => OrderByType.Desc
            };
            //查询筛选

            //序列 int
            var id = Request.Form["id"].FirstOrDefault().ObjectToInt(0);
            if (id > 0)
            {
                where = where.And(p => p.id == id);
            }
            //应用名称 nvarchar
            var name = Request.Form["name"].FirstOrDefault();
            if (!string.IsNullOrEmpty(name))
            {
                where = where.And(p => p.name.Contains(name));
            }
            //应用编码 nvarchar
            var code = Request.Form["code"].FirstOrDefault();
            if (!string.IsNullOrEmpty(code))
            {
                where = where.And(p => p.code.Contains(code));
            }
            //易联云应用id nvarchar
            var clientId = Request.Form["clientId"].FirstOrDefault();
            if (!string.IsNullOrEmpty(clientId))
            {
                where = where.And(p => p.clientId.Contains(clientId));
            }
            //易联云应用密钥 nvarchar
            var clientSecret = Request.Form["clientSecret"].FirstOrDefault();
            if (!string.IsNullOrEmpty(clientSecret))
            {
                where = where.And(p => p.clientSecret.Contains(clientSecret));
            }
            //易联云终端号 nvarchar
            var machineCode = Request.Form["machineCode"].FirstOrDefault();
            if (!string.IsNullOrEmpty(machineCode))
            {
                where = where.And(p => p.machineCode.Contains(machineCode));
            }
            //易联云终端密钥 nvarchar
            var msign = Request.Form["msign"].FirstOrDefault();
            if (!string.IsNullOrEmpty(msign))
            {
                where = where.And(p => p.msign.Contains(msign));
            }
            //打印机名称 nvarchar
            var printerName = Request.Form["printerName"].FirstOrDefault();
            if (!string.IsNullOrEmpty(printerName))
            {
                where = where.And(p => p.printerName.Contains(printerName));
            }
            //联系电话 nvarchar
            var phone = Request.Form["phone"].FirstOrDefault();
            if (!string.IsNullOrEmpty(phone))
            {
                where = where.And(p => p.phone.Contains(phone));
            }
            //访问令牌，API调用时需要，令牌可以重复使用无失效时间，请开发者全局保存 nvarchar
            var accessToken = Request.Form["accessToken"].FirstOrDefault();
            if (!string.IsNullOrEmpty(accessToken))
            {
                where = where.And(p => p.accessToken.Contains(accessToken));
            }
            //更新access_token所需，有效时间35天 nvarchar
            var refreshToken = Request.Form["refreshToken"].FirstOrDefault();
            if (!string.IsNullOrEmpty(refreshToken))
            {
                where = where.And(p => p.refreshToken.Contains(refreshToken));
            }
            //令牌的有效时间，单位秒 (30天),注：该模式下可忽略此参数 int
            var expiresIn = Request.Form["expiresIn"].FirstOrDefault().ObjectToInt(0);
            if (expiresIn > 0)
            {
                where = where.And(p => p.expiresIn == expiresIn);
            }
            //有效期截止时间 datetime
            var expiressEndTime = Request.Form["expiressEndTime"].FirstOrDefault();
            if (!string.IsNullOrEmpty(expiressEndTime))
            {
                if (expiressEndTime.Contains("到"))
                {
                    var dts = expiressEndTime.Split("到");
                    var dtStart = dts[0].Trim().ObjectToDate();
                    where = where.And(p => p.expiressEndTime > dtStart);
                    var dtEnd = dts[1].Trim().ObjectToDate();
                    where = where.And(p => p.expiressEndTime < dtEnd);
                }
                else
                {
                    var dt = expiressEndTime.ObjectToDate();
                    where = where.And(p => p.expiressEndTime > dt);
                }
            }
            //其他参数 nvarchar
            var parameters = Request.Form["parameters"].FirstOrDefault();
            if (!string.IsNullOrEmpty(parameters))
            {
                where = where.And(p => p.parameters.Contains(parameters));
            }
            //创建时间 datetime
            var createTime = Request.Form["createTime"].FirstOrDefault();
            if (!string.IsNullOrEmpty(createTime))
            {
                if (createTime.Contains("到"))
                {
                    var dts = createTime.Split("到");
                    var dtStart = dts[0].Trim().ObjectToDate();
                    where = where.And(p => p.createTime > dtStart);
                    var dtEnd = dts[1].Trim().ObjectToDate();
                    where = where.And(p => p.createTime < dtEnd);
                }
                else
                {
                    var dt = createTime.ObjectToDate();
                    where = where.And(p => p.createTime > dt);
                }
            }
            //是否默认 bit
            var isDefault = Request.Form["isDefault"].FirstOrDefault();
            if (!string.IsNullOrEmpty(isDefault) && isDefault.ToLowerInvariant() == "true")
            {
                where = where.And(p => p.isDefault == true);
            }
            else if (!string.IsNullOrEmpty(isDefault) && isDefault.ToLowerInvariant() == "false")
            {
                where = where.And(p => p.isDefault == false);
            }
            //是否开启 bit
            var isOpen = Request.Form["isOpen"].FirstOrDefault();
            if (!string.IsNullOrEmpty(isOpen) && isOpen.ToLowerInvariant() == "true")
            {
                where = where.And(p => p.isOpen == true);
            }
            else if (!string.IsNullOrEmpty(isOpen) && isOpen.ToLowerInvariant() == "false")
            {
                where = where.And(p => p.isOpen == false);
            }
            //绑定门店 int
            var storeId = Request.Form["storeId"].FirstOrDefault().ObjectToInt(0);
            if (storeId > 0)
            {
                where = where.And(p => p.storeId == storeId);
            }
            //获取数据
            var list = await _coreCmsPrinterServices.QueryPageAsync(where, orderEx, orderBy, pageCurrent, pageSize, true);
            //返回数据
            jm.data = list;
            jm.code = 0;
            jm.count = list.TotalCount;
            jm.msg = "数据调用成功!";
            return jm;
        }
        #endregion

        #region 首页数据============================================================
        // POST: Api/CoreCmsPrinter/GetIndex
        /// <summary>
        /// 首页数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Description("首页数据")]
        public async Task<AdminUiCallBack> GetIndex()
        {
            //返回数据
            var jm = new AdminUiCallBack { code = 0 };

            var stores = await _storeServices.QueryAsync(true, true);
            var thirdPartyEquipment = EnumHelper.EnumToList<GlobalEnumVars.ThirdPartyEquipment>();
            jm.data = new
            {
                stores,
                thirdPartyEquipment
            };

            return jm;
        }
        #endregion

        #region 创建数据============================================================
        // POST: Api/CoreCmsPrinter/GetCreate
        /// <summary>
        /// 创建数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Description("创建数据")]
        public async Task<AdminUiCallBack> GetCreate()
        {
            //返回数据
            var jm = new AdminUiCallBack { code = 0 };

            var stores = await _storeServices.QueryAsync(true, true);
            var thirdPartyEquipment = EnumHelper.EnumToList<GlobalEnumVars.ThirdPartyEquipment>();
            jm.data = new
            {
                stores,
                thirdPartyEquipment
            };

            return jm;
        }
        #endregion

        #region 创建提交============================================================
        // POST: Api/CoreCmsPrinter/DoCreate
        /// <summary>
        /// 创建提交
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("创建提交")]
        public async Task<AdminUiCallBack> DoCreate([FromBody] CoreCmsPrinter entity)
        {
            var jm = await _coreCmsPrinterServices.InsertAsync(entity);
            return jm;
        }
        #endregion

        #region 编辑数据============================================================
        // POST: Api/CoreCmsPrinter/GetEdit
        /// <summary>
        /// 编辑数据
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("编辑数据")]
        public async Task<AdminUiCallBack> GetEdit([FromBody] FMIntId entity)
        {
            var jm = new AdminUiCallBack();

            var model = await _coreCmsPrinterServices.QueryByIdAsync(entity.id, false);
            if (model == null)
            {
                jm.msg = "不存在此信息";
                return jm;
            }
            jm.code = 0;

            var stores = await _storeServices.QueryAsync(true, true);
            var thirdPartyEquipment = EnumHelper.EnumToList<GlobalEnumVars.ThirdPartyEquipment>();
            jm.data = new
            {
                model,
                stores,
                thirdPartyEquipment
            };


            return jm;
        }
        #endregion

        #region 编辑提交============================================================
        // POST: Api/CoreCmsPrinter/Edit
        /// <summary>
        /// 编辑提交
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("编辑提交")]
        public async Task<AdminUiCallBack> DoEdit([FromBody] CoreCmsPrinter entity)
        {
            var jm = await _coreCmsPrinterServices.UpdateAsync(entity);
            return jm;
        }
        #endregion

        #region 删除数据============================================================
        // POST: Api/CoreCmsPrinter/DoDelete/10
        /// <summary>
        /// 单选删除
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("单选删除")]
        public async Task<AdminUiCallBack> DoDelete([FromBody] FMIntId entity)
        {
            var jm = new AdminUiCallBack();

            var model = await _coreCmsPrinterServices.ExistsAsync(p => p.id == entity.id);
            if (!model)
            {
                jm.msg = GlobalConstVars.DataisNo;
                return jm;
            }
            jm = await _coreCmsPrinterServices.DeleteByIdAsync(entity.id);

            return jm;
        }
        #endregion

        #region 刷新Token============================================================
        // POST: Api/CoreCmsPrinter/DoRefreshToken/10
        /// <summary>
        /// 刷新Token
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("刷新Token")]
        public async Task<AdminUiCallBack> DoRefreshToken([FromBody] FMIntId entity)
        {
            var jm = new AdminUiCallBack();

            var model = await _coreCmsPrinterServices.QueryByClauseAsync(p => p.id == entity.id);
            if (model == null)
            {
                jm.msg = GlobalConstVars.DataisNo;
                return jm;
            }

            RefreshYiLianYunToken refreshToken = new RefreshYiLianYunToken
            {
                client_id = model.clientId,
                grant_type = "client_credentials",
                timestamp = CommonHelper.GetDateTimeStamp(DateTime.Now),
                scope = "all",
                id = Guid.NewGuid().ToString()
            };
            refreshToken.sign = CommonHelper.Md5For32((refreshToken.client_id + refreshToken.timestamp + model.clientSecret).ToLowerInvariant()).ToLowerInvariant();
            var resultData = await YiLianYunConfig.AuthUrl.PostJsonAsync(refreshToken).ReceiveJson<YiLianYunAuthResult>();
            //将获取到的数据存入数据库
            if (resultData.error == "0")
            {
                model.accessToken = resultData.body.access_token;
                model.refreshToken = resultData.body.refresh_token;
                model.expiresIn = resultData.body.expires_in;
                model.expiressEndTime = DateTime.Now.AddSeconds(resultData.body.expires_in);

                await _coreCmsPrinterServices.UpdateAsync(
                    p => new CoreCmsPrinter()
                    {
                        accessToken = resultData.body.access_token,
                        refreshToken = resultData.body.refresh_token,
                        expiresIn = resultData.body.expires_in,
                        expiressEndTime = model.expiressEndTime,
                        parameters = JsonConvert.SerializeObject(resultData.body)
                    }, p => p.clientId == model.clientId && p.clientSecret == model.clientSecret, true);

                //await _coreCmsPrinterServices.UpdateAsync(
                //                    p => new CoreCmsPrinter()
                //                    {
                //                        accessToken = resultData.body.access_token,
                //                        refreshToken = resultData.body.refresh_token,
                //                        expiresIn = resultData.body.expires_in,
                //                        expiressEndTime = model.expiressEndTime,
                //                        parameters = JsonConvert.SerializeObject(resultData.body)
                //                    }, p => p.id == model.id, true);

                jm.code = 1;
                jm.msg = "刷新成功";

            }
            else
            {
                jm.msg = "刷新AccessToken：" + resultData.error_description;
                return jm;
            }

            return jm;
        }
        #endregion

        #region 打印测试页============================================================
        // POST: Api/CoreCmsPrinter/DoPrintTest/10
        /// <summary>
        /// 打印测试页
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("打印测试页")]
        public async Task<AdminUiCallBack> DoPrintTest([FromBody] FMIntId entity)
        {
            var jm = new AdminUiCallBack();

            var model = await _coreCmsPrinterServices.QueryByClauseAsync(p => p.id == entity.id);
            if (model == null)
            {
                jm.msg = GlobalConstVars.DataisNo;
                return jm;
            }

            var isNeedToken = false;
            if (string.IsNullOrEmpty(model.accessToken) || model.expiressEndTime == null)
            {
                isNeedToken = true;
            }
            else
            {
                //判断是否过期
                var dt = DateTime.Now;
                if (dt >= model.expiressEndTime)
                {
                    var ts = dt - Convert.ToDateTime(model.expiressEndTime);
                    if (ts.Days > 35)
                    {
                        isNeedToken = true;
                    }
                    else
                    {
                        RefreshYiLianYunToken refreshToken = new RefreshYiLianYunToken
                        {
                            client_id = model.clientId,
                            grant_type = "client_credentials",
                            timestamp = CommonHelper.GetDateTimeStamp(DateTime.Now),
                            scope = "all",
                            id = Guid.NewGuid().ToString()
                        };
                        refreshToken.sign = CommonHelper.Md5For32((refreshToken.client_id + refreshToken.timestamp + model.clientSecret).ToLowerInvariant()).ToLowerInvariant();
                        var resultData = await YiLianYunConfig.AuthUrl.PostJsonAsync(refreshToken).ReceiveJson<YiLianYunAuthResult>();
                        //将获取到的数据存入数据库
                        if (resultData.error == "0")
                        {
                            model.accessToken = resultData.body.access_token;
                            model.refreshToken = resultData.body.refresh_token;
                            model.expiresIn = resultData.body.expires_in;
                            model.expiressEndTime = DateTime.Now.AddSeconds(resultData.body.expires_in);

                            //await _coreCmsPrinterServices.UpdateAsync(
                            //    p => new CoreCmsPrinter()
                            //    {
                            //        accessToken = resultData.body.access_token,
                            //        refreshToken = resultData.body.refresh_token,
                            //        expiresIn = resultData.body.expires_in,
                            //        expiressEndTime = model.expiressEndTime,
                            //        parameters = JsonConvert.SerializeObject(resultData.body)
                            //    }, p => p.id == model.id, true);

                            await _coreCmsPrinterServices.UpdateAsync(
                                p => new CoreCmsPrinter()
                                {
                                    accessToken = resultData.body.access_token,
                                    refreshToken = resultData.body.refresh_token,
                                    expiresIn = resultData.body.expires_in,
                                    expiressEndTime = model.expiressEndTime,
                                    parameters = JsonConvert.SerializeObject(resultData.body)
                                }, p => p.clientId == model.clientId && p.clientSecret == model.clientSecret, true);

                        }
                        else
                        {
                            jm.msg = "刷新AccessToken：" + resultData.error_description;
                            return jm;
                        }
                    }
                }
            }

            if (isNeedToken)
            {
                var getToken = new YiLianYunParam
                {
                    client_id = model.clientId,
                    grant_type = "client_credentials",
                    timestamp = CommonHelper.GetDateTimeStamp(DateTime.Now),
                    scope = "all",
                    id = Guid.NewGuid().ToString()
                };
                getToken.sign = CommonHelper.Md5For32((getToken.client_id + getToken.timestamp + model.clientSecret).ToLowerInvariant()).ToLowerInvariant();

                var resultData = await YiLianYunConfig.AuthUrl.PostJsonAsync(getToken).ReceiveJson<YiLianYunAuthResult>();
                //将获取到的数据存入数据库
                if (resultData.error == "0")
                {
                    model.accessToken = resultData.body.access_token;
                    model.refreshToken = resultData.body.refresh_token;
                    model.expiresIn = resultData.body.expires_in;
                    model.expiressEndTime = DateTime.Now.AddSeconds(resultData.body.expires_in);

                    //await _coreCmsPrinterServices.UpdateAsync(
                    //    p => new CoreCmsPrinter()
                    //    {
                    //        accessToken = resultData.body.access_token,
                    //        refreshToken = resultData.body.refresh_token,
                    //        expiresIn = resultData.body.expires_in,
                    //        expiressEndTime = model.expiressEndTime,
                    //        parameters = JsonConvert.SerializeObject(resultData.body)
                    //    }, p => p.id == model.id, true);

                    await _coreCmsPrinterServices.UpdateAsync(
                        p => new CoreCmsPrinter()
                        {
                            accessToken = resultData.body.access_token,
                            refreshToken = resultData.body.refresh_token,
                            expiresIn = resultData.body.expires_in,
                            expiressEndTime = model.expiressEndTime,
                            parameters = JsonConvert.SerializeObject(resultData.body)
                        }, p => p.clientId == model.clientId && p.clientSecret == model.clientSecret, true);

                }
                else
                {
                    jm.msg = "获取AccessToken：" + resultData.error_description;
                    return jm;
                }
            }

            //获取打印机是否在线
            var statusParam = new GetPrintStatusParam
            {
                client_id = model.clientId,
                access_token = model.accessToken,
                machine_code = model.machineCode,
                timestamp = CommonHelper.GetDateTimeStamp(DateTime.Now),
                id = Guid.NewGuid().ToString()
            };
            statusParam.sign = CommonHelper.Md5For32((statusParam.client_id + statusParam.timestamp + model.clientSecret).ToLowerInvariant()).ToLowerInvariant();

            var getPrintStatusResult = await YiLianYunConfig.GetPrintStatusUrl.PostJsonAsync(statusParam).ReceiveJson<YiLianYunGetPrintStatusResult>();
            if (getPrintStatusResult.error != "0")
            {
                jm.msg = "获取打印机在线状态：" + getPrintStatusResult.error_description;
                return jm;
            }
            else
            {
                switch (getPrintStatusResult.body.state)
                {
                    case "0":
                        jm.msg = "机器未在线";
                        return jm;
                    case "2":
                        jm.msg = "机器缺纸";
                        return jm;
                    default:
                        {
                            var order = new CoreCmsOrder()
                            {
                                createTime = DateTime.Now,
                                orderId = DateTime.Now.ToLongDateString(),
                                pointMoney = 10,
                                orderDiscountAmount = 0,
                                goodsDiscountAmount = 0,
                                couponDiscountAmount = 0,
                                orderAmount = 199,
                                shipAreaName = "湖南省",
                                shipAddress = "怀化市鹤城区迎丰中路佳慧中央商厦A栋1513-1514（南山田舍）",
                                shipName = "大灰灰",
                                shipMobile = "19145919666"
                            };
                            var printStr = YiLianYunConfig.PrintTmpModel(order);

                            //小票打印
                            WordPrintRespone wordPrintRespone = new WordPrintRespone
                            {
                                client_id = model.clientId,
                                access_token = model.accessToken,
                                machine_code = model.machineCode,
                                content = printStr.ToString(),
                                origin_id = order.orderId,
                                timestamp = CommonHelper.GetDateTimeStamp(DateTime.Now)
                            };
                            wordPrintRespone.sign = CommonHelper.Md5For32((wordPrintRespone.client_id + wordPrintRespone.timestamp + model.clientSecret).ToLowerInvariant()).ToLowerInvariant();
                            wordPrintRespone.id = Guid.NewGuid().ToString();

                            //打印文本：缺少参数！请检查参数信息！！或更改下请求头：Content-Type:application/x-www-form-urlencoded
                            var resultData = await YiLianYunConfig.PrintTextUrl.WithHeader("Content-Type", "application/x-www-form-urlencoded").PostUrlEncodedAsync(wordPrintRespone).ReceiveJson<YiLianYunGetPrintTextResult>();
                            //当token返回失败时
                            if (resultData.error != "0")
                            {
                                jm.msg = "打印文本：" + resultData.error_description;
                                return jm;
                            }
                            else
                            {
                                jm.code = 1;
                                jm.msg = "打印成功";
                            }

                            break;
                        }
                }
            }
            return jm;
        }



        #endregion

        #region 预览数据============================================================
        // POST: Api/CoreCmsPrinter/GetDetails/10
        /// <summary>
        /// 预览数据
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("预览数据")]
        public async Task<AdminUiCallBack> GetDetails([FromBody] FMIntId entity)
        {
            var jm = new AdminUiCallBack();

            var model = await _coreCmsPrinterServices.QueryByIdAsync(entity.id, false);
            if (model == null)
            {
                jm.msg = "不存在此信息";
                return jm;
            }
            jm.code = 0;

            var stores = await _storeServices.QueryAsync(true, true);
            var thirdPartyEquipment = EnumHelper.EnumToList<GlobalEnumVars.ThirdPartyEquipment>();
            jm.data = new
            {
                model,
                stores,
                thirdPartyEquipment
            };

            return jm;
        }
        #endregion

        #region 设置是否默认============================================================
        // POST: Api/CoreCmsPrinter/DoSetisDefault/10
        /// <summary>
        /// 设置是否默认
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("设置是否默认")]
        public async Task<AdminUiCallBack> DoSetIsDefault([FromBody] FMUpdateBoolDataByIntId entity)
        {
            var jm = new AdminUiCallBack();

            var oldModel = await _coreCmsPrinterServices.QueryByIdAsync(entity.id, false);
            if (oldModel == null)
            {
                jm.msg = "不存在此信息";
                return jm;
            }
            oldModel.isDefault = (bool)entity.data;

            //判断是否除了自己其他都不是默认
            var haveOtherDefault = await _coreCmsPrinterServices.ExistsAsync(p => p.isDefault == true && p.id != entity.id);
            if (haveOtherDefault == false && oldModel.isDefault == false)
            {
                jm.msg = "至少有一个要是默认打印机";
                return jm;
            }

            var bl = await _coreCmsPrinterServices.UpdateAsync(p => new CoreCmsPrinter() { isDefault = oldModel.isDefault }, p => p.id == oldModel.id, true);

            //将其他打印机设置为非默认
            if (bl && oldModel.isDefault == true)
            {
                await _coreCmsPrinterServices.UpdateAsync(p => new CoreCmsPrinter() { isDefault = false }, p => p.id != oldModel.id, true);
            }

            jm.code = bl ? 0 : 1;
            jm.msg = bl ? GlobalConstVars.EditSuccess : GlobalConstVars.EditFailure;

            return jm;
        }
        #endregion

        #region 设置是否开启============================================================
        // POST: Api/CoreCmsPrinter/DoSetisOpen/10
        /// <summary>
        /// 设置是否开启
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("设置是否开启")]
        public async Task<AdminUiCallBack> DoSetIsOpen([FromBody] FMUpdateBoolDataByIntId entity)
        {
            var jm = new AdminUiCallBack();

            var oldModel = await _coreCmsPrinterServices.QueryByIdAsync(entity.id, false);
            if (oldModel == null)
            {
                jm.msg = "不存在此信息";
                return jm;
            }
            oldModel.isOpen = (bool)entity.data;

            var bl = await _coreCmsPrinterServices.UpdateAsync(p => new CoreCmsPrinter() { isOpen = oldModel.isOpen }, p => p.id == oldModel.id);
            jm.code = bl ? 0 : 1;
            jm.msg = bl ? GlobalConstVars.EditSuccess : GlobalConstVars.EditFailure;

            return jm;
        }
        #endregion


    }
}
